package com.romadan.core.wolfram;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;

import com.romadan.core.wolfram.gui.DialogWindow;

public class KernelDir {
	private  final String nameKernelDirFile = "kernelDir.bess";
	private  final String kernelName = "MathKernel.exe";
	public static Object monitor = new Object();
	
	public String getKernelFile(){
		String fileWolframKernel = readKernelFromFile();
		if (!checkFileKernel(fileWolframKernel)) {
			fileWolframKernel = createFile();
		}
		return fileWolframKernel;
	}
	
	private  String readKernelFromFile() {
		String filename = ".//" + nameKernelDirFile;
		return readFromFile(filename);
	}

	private String createFile() {
		DialogWindow window = new DialogWindow();
		window.setVisible(true);
		synchronized (monitor) {
			try {
				monitor.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return window.getRequiredFile().getAbsolutePath();
	}
	
	private  String readFromFile(String filename) {
		InputStreamReader isr;
		String str = "";
		try {
			isr = new InputStreamReader(new FileInputStream(filename),
					"windows-1251");

			BufferedReader in = new BufferedReader(isr);
			str = in.readLine();
			in.close();
			if (!checkFileKernel(str)) {
				JOptionPane.showMessageDialog(null, "Kernel file " + kernelName
						+ " not found.", "WolframOptimus",
						JOptionPane.ERROR_MESSAGE);
				delFile(filename);
				
			}

		} catch (IOException e) {
			
		}
		return str;
	}

	private  void delFile(String pathDel) {
		File temp = new File(pathDel);
		temp.delete();
	}

	private boolean checkFileKernel(String file) {
		File kernel = new File(file);
		return kernel.exists() && kernel.isFile();
	}
}
